import { userStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'


nProgress.configure({
  showSpinner: false
})


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path : '/login', component : () => import('@/views/login/index.vue'),
      meta : { title : '登录' }
    },
    {
      path : '/user/patient', component : () => import('@/views/User/PatientPage.vue'),
      meta : { title : '家庭档案' }
    },
    {
      path : '/' , component : () => import('@/views/Layout/index.vue'),
      redirect : '/home' ,
      children : [
        { path : '/home' , component : () => import('@/views/Home/index.vue') , meta : { title : '首页' } } ,
        { path : '/user' , component : () => import('@/views/User/index.vue') , meta : { title : '健康百科' } } ,
        { path : '/article' , component : () => import('@/views/Article/index.vue') , meta : { title : '消息通知' } } ,
        { path : '/notify' , component : () => import('@/views/Notify/index.vue'), meta : { title : '个人中心' } } ,
      ]
    }
],
})


// 全局的前置导航
router.beforeEach((to, from ,next)=>{
  nProgress.start()
  // 获取token
  const store = userStore()
  const whiteList = ['login']
  // 如果没有token且没有在白名单里，跳转到登录页
  // if(!store.user && !whiteList.includes(to.path))  return '/login'

  // 判断是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  if (requiresAuth) {
    if (!store.user) {
      // 如果未登录且访问受保护页面，跳转登录页
      if (!whiteList.includes(to.path)) {
        return next({ name: 'Login' })
      }
    } else {
      // 已登录但访问登录页，则跳转首页
      if (to.name === 'Login') {
        return next({ name: 'Dashboard' })
      }
      return next()
    }
  }

  // 白名单页面直接放行
  if (whiteList.includes(to.path)) {
    return next()
  }

  // 默认放行
  return next()
})


// 全局的后置导航
router.afterEach((to)=>{
  document.title = `${ to.meta.title || '' }-优医问诊`
  nProgress.done()
})

export default router

